package brainbots.brains;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JComponent;

import brainbots.bot.Body;


public class ManuallyControlledBrain implements Brain {

    private int[] motorCommands = new int[4];

    private static final int TURN_ON=0;
    private static final int TURN_OFF=1;
    private static final int LEAVE=2;

    public ManuallyControlledBrain()
    {
        for (int i =0;i<motorCommands.length;++i){
            motorCommands[i]=LEAVE;
        }
    }
    
	/**Attach bot controls to the compoennt*/
	public void attach(JComponent comp){
		KeyListener kl = new KeyAdapter(){
			@Override
			public void keyPressed(KeyEvent arg0) {
				int motorIdx = getMotorIndex(arg0.getKeyCode());
				if (motorIdx <0)
					return;
				motorCommands[motorIdx] = TURN_ON;
			}

			@Override
			public void keyReleased(KeyEvent arg0) {
				int motorIdx = getMotorIndex(arg0.getKeyCode());
				if (motorIdx <0)
					return;
				motorCommands[motorIdx] = TURN_OFF;
            }

		};
		comp.addKeyListener(kl);
		
	}
	protected int getMotorIndex(int keyCode) {
		switch (keyCode){
		case KeyEvent.VK_W:
			return 0;
		case KeyEvent.VK_E:
			return 1;
		case KeyEvent.VK_A:
			return 2;
		case KeyEvent.VK_D:
			return 3;
		}
		return -1;
	}

    public void simulate(double dt, Body bot)
    {
        for (int i = 0;i< motorCommands.length;++i){
            switch (motorCommands[i]){
            case LEAVE:
                break;
            case TURN_ON:
                bot.setMotor(i, 1.0);
                break;
            case TURN_OFF:
                bot.setMotor(i, 0.0);
                break;
            default:
                throw new RuntimeException("Unknown motor command");
            }
        }
    }


}
